<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>逾期等级统计测试页面</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f5f5f5;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        
        h1, h2 {
            color: #333;
        }
        
        .query-panel {
            background-color: #f9f9f9;
            padding: 15px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        
        .form-group {
            display: inline-block;
            margin-right: 15px;
            margin-bottom: 10px;
        }
        
        label {
            display: inline-block;
            width: 100px;
            font-weight: bold;
        }
        
        input, select {
            padding: 5px 10px;
            border: 1px solid #ddd;
            border-radius: 3px;
            width: 150px;
        }
        
        button {
            padding: 8px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-left: 10px;
        }
        
        button:hover {
            background-color: #45a049;
        }
        
        button.detail-btn {
            padding: 5px 15px;
            font-size: 12px;
            background-color: #2196F3;
        }
        
        button.detail-btn:hover {
            background-color: #0b7dda;
        }
        
        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 20px;
        }
        
        th, td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        
        th {
            background-color: #4CAF50;
            color: white;
        }
        
        tr:hover {
            background-color: #f5f5f5;
        }
        
        .level-1 { background-color: #FFFFFF !important; }
        .level-2 { background-color: #FFE4B5 !important; }
        .level-3 { background-color: #FFA500 !important; color: white; }
        .level-4 { background-color: #FF0000 !important; color: white; }
        .level-5 { background-color: #8B0000 !important; color: white; }
        
        .priority-low { color: #4CAF50; font-weight: bold; }
        .priority-normal { color: #FF9800; font-weight: bold; }
        .priority-medium { color: #FF5722; font-weight: bold; }
        .priority-high { color: #F44336; font-weight: bold; }
        .priority-critical { color: #B71C1C; font-weight: bold; }
        
        .loading {
            text-align: center;
            padding: 20px;
            color: #999;
        }
        
        .error {
            color: red;
            padding: 10px;
            background-color: #ffebee;
            border-radius: 4px;
            margin: 10px 0;
        }
        
        .pagination {
            margin-top: 20px;
            text-align: center;
        }
        
        .pagination button {
            margin: 0 5px;
            padding: 5px 15px;
            background-color: #2196F3;
        }
        
        .pagination button:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        
        .stat-card {
            display: inline-block;
            margin: 10px;
            padding: 15px;
            border-radius: 5px;
            min-width: 200px;
            text-align: center;
        }
        
        .stat-card h3 {
            margin: 0 0 10px 0;
        }
        
        .stat-card .number {
            font-size: 24px;
            font-weight: bold;
            margin: 5px 0;
        }
        
        .stat-card .label {
            color: #666;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>逾期等级统计测试页面</h1>
        
        <!-- 查询面板 -->
        <div class="query-panel">
            <h2>查询条件</h2>
            <div class="form-group">
                <label>客户ID：</label>
                <input type="number" id="customerId" placeholder="可选">
            </div>
            <div class="form-group">
                <label>客户名称：</label>
                <input type="text" id="customerName" placeholder="可选">
            </div>
            <div class="form-group">
                <label>开始时间：</label>
                <input type="date" id="startTime">
            </div>
            <div class="form-group">
                <label>结束时间：</label>
                <input type="date" id="endTime">
            </div>
            <div class="form-group">
                <label>台账标识：</label>
                <select id="regionId">
                    <option value="">全部</option>
                    <option value="0">寿光</option>
                    <option value="1">河北</option>
                    <option value="2">聊城</option>
                    <option value="3">云南</option>
                </select>
            </div>
            <br>
            <button onclick="loadStatistics()">查询统计</button>
            <button onclick="resetForm()">重置</button>
        </div>
        
        <!-- 统计结果 -->
        <div id="statisticsResult">
            <h2>逾期等级统计</h2>
            <div id="statisticsCards"></div>
            <div id="statisticsTable"></div>
        </div>
        
        <!-- 详情结果 -->
        <div id="detailResult" style="display: none;">
            <h2>逾期等级详情</h2>
            <p><strong>当前查询等级：</strong><span id="currentLevel"></span></p>
            <button onclick="backToStatistics()">返回统计</button>
            <div id="detailTable"></div>
            <div id="pagination" class="pagination"></div>
        </div>
    </div>
    
    <script>
        let currentPage = 1;
        let currentLevel = null;
        
        // 加载统计数据
        function loadStatistics() {
            const params = getQueryParams();
            const queryString = new URLSearchParams(params).toString();
            
            document.getElementById('statisticsCards').innerHTML = '<div class="loading">加载中...</div>';
            document.getElementById('statisticsTable').innerHTML = '';
            
            fetch(`/finance/customerCollectionAlertRecord/levelStatistics?${queryString}`)
                .then(response => response.json())
                .then(result => {
                    if (result.code === 0) {
                        renderStatistics(result.data);
                    } else {
                        showError('statisticsCards', result.msg || '查询失败');
                    }
                })
                .catch(error => {
                    showError('statisticsCards', '网络错误: ' + error.message);
                });
        }
        
        // 渲染统计数据
        function renderStatistics(data) {
            // 渲染卡片
            let cardsHtml = '';
            data.forEach(item => {
                const levelClass = `level-${item.overdueLevel}`;
                cardsHtml += `
                    <div class="stat-card ${levelClass}">
                        <h3>${item.overdueLevelName} (${item.priority})</h3>
                        <div class="number">${item.orderCount || 0}</div>
                        <div class="label">订单数量</div>
                        <div class="number">¥${formatMoney(item.totalUnreceivedAmount || 0)}</div>
                        <div class="label">未回款金额</div>
                        <button class="detail-btn" onclick="viewDetail(${item.overdueLevel})">查看详情</button>
                    </div>
                `;
            });
            document.getElementById('statisticsCards').innerHTML = cardsHtml || '<div class="loading">暂无数据</div>';
            
            // 渲染表格
            let tableHtml = `
                <table>
                    <thead>
                        <tr>
                            <th>等级</th>
                            <th>天数范围</th>
                            <th>优先级</th>
                            <th>订单数量</th>
                            <th>未回款金额</th>
                            <th>订单总金额</th>
                            <th>已回款金额</th>
                            <th>平均逾期天数</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
            `;
            
            data.forEach(item => {
                const levelClass = `level-${item.overdueLevel}`;
                tableHtml += `
                    <tr class="${levelClass}">
                        <td>${item.overdueLevelName}</td>
                        <td>${item.overdueDaysRange}</td>
                        <td>${item.priority}</td>
                        <td>${item.orderCount || 0}</td>
                        <td>¥${formatMoney(item.totalUnreceivedAmount || 0)}</td>
                        <td>¥${formatMoney(item.totalOrderAmount || 0)}</td>
                        <td>¥${formatMoney(item.totalReceivedAmount || 0)}</td>
                        <td>${item.avgOverdueDays || 0}天</td>
                        <td><button class="detail-btn" onclick="viewDetail(${item.overdueLevel})">查看详情</button></td>
                    </tr>
                `;
            });
            
            tableHtml += '</tbody></table>';
            document.getElementById('statisticsTable').innerHTML = tableHtml;
        }
        
        // 查看详情
        function viewDetail(level) {
            currentLevel = level;
            currentPage = 1;
            loadDetail();
            
            document.getElementById('statisticsResult').style.display = 'none';
            document.getElementById('detailResult').style.display = 'block';
            
            const levelNames = ['', '15天以内', '15-29天', '30-59天', '60-89天', '90天以上'];
            document.getElementById('currentLevel').textContent = levelNames[level] || '未知';
        }
        
        // 加载详情数据
        function loadDetail() {
            const params = getQueryParams();
            params.overdueLevel = currentLevel;
            params.page = currentPage;
            params.limit = 10;
            
            const queryString = new URLSearchParams(params).toString();
            
            document.getElementById('detailTable').innerHTML = '<div class="loading">加载中...</div>';
            
            fetch(`/finance/customerCollectionAlertRecord/levelDetail?${queryString}`)
                .then(response => response.json())
                .then(result => {
                    if (result.code === 0) {
                        renderDetail(result.data);
                    } else {
                        showError('detailTable', result.msg || '查询失败');
                    }
                })
                .catch(error => {
                    showError('detailTable', '网络错误: ' + error.message);
                });
        }
        
        // 渲染详情数据
        function renderDetail(data) {
            let tableHtml = `
                <table>
                    <thead>
                        <tr>
                            <th>客户名称</th>
                            <th>订单编号</th>
                            <th>订单时间</th>
                            <th>订单金额</th>
                            <th>已回款</th>
                            <th>未回款</th>
                            <th>逾期天数</th>
                            <th>预警阈值</th>
                            <th>预警级别</th>
                        </tr>
                    </thead>
                    <tbody>
            `;
            
            if (data.records && data.records.length > 0) {
                data.records.forEach(item => {
                    tableHtml += `
                        <tr>
                            <td>${item.customerName}</td>
                            <td>${item.docNo}</td>
                            <td>${item.orderTime}</td>
                            <td>¥${formatMoney(item.orderAmount)}</td>
                            <td>¥${formatMoney(item.receivedAmount)}</td>
                            <td>¥${formatMoney(item.unreceivedAmount)}</td>
                            <td>${item.overdueDays}天</td>
                            <td>${item.alertThreshold}天</td>
                            <td>${item.alertLevelName}</td>
                        </tr>
                    `;
                });
            } else {
                tableHtml += '<tr><td colspan="9" style="text-align: center;">暂无数据</td></tr>';
            }
            
            tableHtml += '</tbody></table>';
            document.getElementById('detailTable').innerHTML = tableHtml;
            
            // 渲染分页
            renderPagination(data.current, data.total, data.size);
        }
        
        // 渲染分页
        function renderPagination(current, total, size) {
            const totalPages = Math.ceil(total / size);
            let paginationHtml = `
                <button ${current <= 1 ? 'disabled' : ''} onclick="changePage(${current - 1})">上一页</button>
                <span>第 ${current} / ${totalPages} 页 (共 ${total} 条)</span>
                <button ${current >= totalPages ? 'disabled' : ''} onclick="changePage(${current + 1})">下一页</button>
            `;
            document.getElementById('pagination').innerHTML = paginationHtml;
        }
        
        // 切换页码
        function changePage(page) {
            currentPage = page;
            loadDetail();
        }
        
        // 返回统计
        function backToStatistics() {
            document.getElementById('statisticsResult').style.display = 'block';
            document.getElementById('detailResult').style.display = 'none';
        }
        
        // 获取查询参数
        function getQueryParams() {
            const params = {};
            
            const customerId = document.getElementById('customerId').value;
            if (customerId) params.customerId = customerId;
            
            const customerName = document.getElementById('customerName').value;
            if (customerName) params.customerName = customerName;
            
            const startTime = document.getElementById('startTime').value;
            if (startTime) params.startTime = startTime;
            
            const endTime = document.getElementById('endTime').value;
            if (endTime) params.endTime = endTime;
            
            const regionId = document.getElementById('regionId').value;
            if (regionId !== '') params.regionId = regionId;
            
            return params;
        }
        
        // 重置表单
        function resetForm() {
            document.getElementById('customerId').value = '';
            document.getElementById('customerName').value = '';
            document.getElementById('startTime').value = '';
            document.getElementById('endTime').value = '';
            document.getElementById('regionId').value = '';
        }
        
        // 格式化金额
        function formatMoney(amount) {
            return Number(amount).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        }
        
        // 显示错误
        function showError(elementId, message) {
            document.getElementById(elementId).innerHTML = `<div class="error">${message}</div>`;
        }
        
        // 页面加载时自动查询
        window.onload = function() {
            loadStatistics();
        };
    </script>
</body>
</html>
